<template>
  <el-cascader
    v-model="selectVal"
    :options="options"
    separator=" / "
    :props="{
      expandTrigger: 'hover',
      value: 'id',
      label: 'name'
    }"
    placeholder="请选择商品类别"
    popper-class="CcategoryCascaderPopper"
    v-bind="$attrs"
    @change="change"
  >
    <template slot-scope="{ data }">
      <Cimage v-if="data.icon" :src="data.icon[0].url" fit="cover" width="30px" height="30px" class="mr10" />
      <span>{{ data.name }}</span>
    </template>
  </el-cascader>
</template>
<script>
import {
  categoryGetOne,
  categoryGetTwo
} from '@/api/category'
export default {
  // 商品分类级联选择器
  name: 'CcategoryCascader',
  props: {
    categoryId: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      options: []
    }
  },
  computed: {
    selectVal: {
      get() {
        return this.categoryId
      },
      set(val) {
        this.$emit('update:categoryId', val) // 在这里进行更新
        return val
      }
    }
  },
  watch: {
    categoryId: {
      handler(n) {
        this.getList()
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 初始化数据
    async getList() {
      if (this.options.length === 0) { // 没有数据才更新
        const res = await categoryGetOne()
        if (res.code === 0) {
          const { data: oneData } = res
          const two_res = await categoryGetTwo()
          if (two_res.code === 0) {
            const { data: twoData } = two_res
            oneData.forEach(item => { // 匹配数据
              item.id = item.id.toString()
              item['children'] = []
              twoData.forEach(it => {
                it.id = it.id.toString()
                // eslint-disable-next-line eqeqeq
                if (item.id == it.parentId) {
                  item['children'].push(it)
                }
              })
            })
            this.options = oneData
            this.$forceUpdate()
          }
        }
      }
    },
    // 更新值（回调）
    change(value) {
      // if (value.length > 0) {
      //   this.$emit('update:categoryId', value[value.length - 1])
      // } else {
      //   this.$emit('update:categoryId', '')
      // }
    }
  }
}
</script>
<style lang="scss">
.CcategoryCascaderPopper{
  .el-cascader-node__label{
    display: flex;
    align-items: center;
  }
  .el-cascader-node:not(.is-disabled):hover, .el-cascader-node:not(.is-disabled):focus {
    background: #EBEEF5;
  }
}
</style>
